<template>
  <el-dialog
    title="批量用户切换部门操作"
    :visible.sync="dialogVisible"
    width="55%"
    top="10vh"
    :before-close="closeUserBatchMoveDialogHandle"
    :close-on-click-modal="false"
    class="user-batch-move-dialog"
  >
    <el-row :gutter="10">
      <el-col :span="7">
        <el-card>
          <div slot="header">
            <span>可选用户列表</span>
          </div>
          <div class="user-filter">
            <el-input :disabled="userList.length === 0" v-model="userFilterText" size="mini" placeholder="请输入内容"></el-input>
          </div>
          <div class="user-list">
            <div v-for="(user, index) in userList" :key="user.userId" class="user">
              <span>{{ user.username }}</span>
              <el-button type="text" icon="el-icon-plus" @click="addUserHandle(user, index)" class="add-btn">添加</el-button>
            </div>
          </div>

        </el-card>

      </el-col>
      <el-col :span="17">
        <el-card class="box-card">
          <div slot="header">
            <span>已选用户列表</span>
          </div>
          <el-table :data="userSelectList" :height="400" :max-height="400">
            <el-table-column prop="deptName" header-align="center" align="center" label="所属部门" ></el-table-column>
            <el-table-column prop="username" header-align="center" align="center" label="姓名" ></el-table-column>
            <el-table-column prop="status" header-align="center" align="center" label="状态">
              <template v-slot="scope">
                <el-tag :type="scope.row.status === 0 ? 'success' : 'danger'">
                  {{ scope.row.status === 0 ? '可用' : '不可用' }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column header-align="center" align="center" label="操作" width="80">
              <template v-slot="scope">
                <el-button type="text" @click="subUserHandle(scope)" class="danger-color">取 消</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-col>
    </el-row>
    <el-card style="margin-top: 10px;">
      <el-form inline :model="userForm" :rules="userRules" ref="userForm" label-width="85px" class="user-form">
        <el-row type="flex" justify="center">
          <el-col :span="9">
            <el-form-item label="所属部门">
              <span :style="{color: themeColor}">{{ deptName }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="13">
            <el-form-item label="新部门" prop="nextDeptId" class="next-dept-id">
              <tree-select :value="userForm.nextDeptId"
                           :options="deptTree"
                           :disabled="buttonLoad"
                           show-count
                           clearValueText="清除选择"
                           :normalizer="normalizer"
                           @select="deptTreeChangeHandle"
                           placeholder="请选择父级部门"
                           class="dept-tree-select" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row >
          <el-col :span="23" :offset="1">
            <el-form-item label="切换原因" prop="moveRemark" class="audit-remark">
              <el-input type="textarea"
                        :autosize="{ minRows: 2, maxRows: 4 }"
                        maxlength="100"
                        show-word-limit
                        resize="none"
                        placeholder="请输入内容"
                        v-model="userForm.moveRemark"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-card>
    <span slot="footer">
        <el-button @click="closeUserBatchMoveDialogHandle">取 消</el-button>
      <el-button :disabled="buttonLoad || userSelectList.length === 0" type="primary" @click="submitHandle">确 定</el-button>
    </span>
  </el-dialog>
</template>

<script>
  // 树形选择插件
  import TreeSelect from '@riophae/vue-treeselect'
  // 树形插件样式
  import '@riophae/vue-treeselect/dist/vue-treeselect.css'

  export default {
    name: "user-batch-move",
    components: { TreeSelect },
    props: {
      // 弹出框是否显示
      dialogVisible: {
        type: Boolean,
        default: false
      }
    },
    data() {
      return {
        // 原部门名称
        deptName: undefined,
        // 用户切换部门表单对象
        userForm: {
          // 用户主键
          userIds: undefined,
          // 原所属部门主键
          preDeptId: undefined,
          // 新部门主键
          nextDeptId: undefined,
          // 切换模式[0-单个用户 1-批量切换 2-全部切换]
          moveMode: 1,
          // 切换原因
          moveRemark: ''
        },
        // 可选择用户列表
        userList: [],
        // 已选择用户列表
        userSelectList: [],
        // 可选择用户检索内容
        userFilterText: '',
        // 部门树数据列表
        deptTree: [],
        // 按钮是否可被点击[false-可以被点击 true-不可被点击]
        buttonLoad: false,
        // 用户切换部门表单校验规则
        userRules: {
          nextDeptId: [
            { required: true, message: '请选择新部门', trigger: 'blur' }
          ],
          moveRemark: [
            { required: true, message: '切换原因不能为空', trigger: 'blur' }
          ],
        }
      }
    },
    computed: {
      // 主题颜色
      themeColor() {
        return this.$store.state.settings.theme
      },
    },
    methods: {
      /**
       * 批量用户切换部门弹出框
       * @param {string} deptId   部门主键
       * @param {string} deptName 部门名称
       */
      initUserBatchMoveDialog(deptId, deptName) {
        this.deptName = deptName;
        this.userForm.preDeptId = deptId;

        this.getSimpleUserList(deptId);
        this.getDeptTree()
      },
      /**
       * 获取用户简单数据方法
       * @param {string} deptId 部门主键
       */
      getSimpleUserList(deptId) {
        // 开始加载用户简单数据
        this.buttonLoad = true;
        this.$axios.$get('/sys/dept-user/simple/list', { params: { deptId }})
          .then(({ data }) => {
            this.userList = data;
          })
          .catch(() => {})
          .finally(() => {
            // 用户简单数据加载结束
            this.buttonLoad = false;
          })
      },
      /**
       * 获取部门数据树方法
       */
      getDeptTree() {
        // 开始部门树加载
        this.buttonLoad = true;
        this.$axios.$get('/sys/dept/children/tree')
          .then(({ data }) => {
            this.deptTree.push(data);
          })
          .catch(() => {})
          .finally(() => {
            // 部门树加载结束
            this.buttonLoad = false;
          })
      },
      /**
       * 批量用户切换部门确认事件
       */
      submitHandle() {
        this.$refs.userForm.validate((valid) => {
          if (!valid) {
            return false;
          }
          let userForm = this.userForm;
          if (userForm.preDeptId === userForm.nextDeptId) {
            this.notify('', '温馨提示', '新所属部门不能与原所属部门一致。');
            return false;
          }
          userForm.userIds = this.userSelectList.map(user => user.userId);
          console.log('userForm', userForm)
          // 开始批量用户切换部门
          this.buttonLoad = true;
          this.$axios.$post('/sys/user-dept/flow/batch/move', userForm)
            .then(() => {
              this.notify('success', '操作成功', '批量用户切换部门操作成功');

              this.closeUserBatchMoveDialogHandle();
            })
            .catch(() => {})
            .finally(() => {
              // 批量用户切换部门结束
              this.buttonLoad = false;
            })
        });
      },
      /**
       * 选择切换部门的用户事件
       * @param {Object} user  用户对象
       * @param {number} index 用户所在列表的下标
       */
      addUserHandle(user, index) {
        user.deptName = this.deptName;
        // 选择用户
        this.userSelectList.push(user);
        // 删除原列表的数据
        this.userList.splice(index, 1);
      },
      /**
       * 用户取消切换部门事件
       * @param {Object} userScope 用户数据行对象
       */
      subUserHandle(userScope) {
        // 取消用户选择
        this.userSelectList.splice(userScope.$index, 1);
        // 用户回到可选用户列表
        this.userList.push(userScope.row);
      },
      /**
       * 部门树数据转化成插件可识别数据
       * @param node
       * @returns {{children, id: (string|(function(): string)|*), label}}
       */
      normalizer(node) {
        if (node.children && !node.children.length) {
          delete node.children;
        }
        return {
          id: node.deptId,
          label: node.deptName,
          isDisabled: node.disabled,
          children: node.children
        };
      },
      /**
       * 部门树选择项发生改变事件
       * @param node        部门选择树选中节点
       * @param instanceId
       */
      deptTreeChangeHandle(node, instanceId) {
        let userForm = this.userForm
        userForm.nextDeptId = node.deptId
        // 清除校验状态
        this.$refs.userForm.clearValidate(['nextDeptId'])
      },
      /**
       * 关闭用户批量切换部门弹出框事件
       */
      closeUserBatchMoveDialogHandle() {
        this.deptName = undefined;
        // 清空表单校验信息
        this.$refs.userForm.clearValidate()
        this.userForm = {
          userIds: undefined,
          preDeptId: undefined,
          nextDeptId: undefined,
          roleIds: [],
          moveMode: 1,
          moveRemark: ''
        };
        this.userList = [];
        this.userSelectList = [];
        // 清理部门树数据
        this.deptTree = [];
        // 向上传递事件
        this.$emit('close-user-batch-move-dialog');
      }
    }
  }
</script>

<style scoped>
  .user-batch-move-dialog >>> .el-dialog__body {
    padding: 10px 20px;
  }
  .user-batch-move-dialog >>> .el-card__header {
    padding: 10px 20px;
  }
  .user-batch-move-dialog >>> .el-card__body {
    padding: 10px;
  }
  .user-filter {
    margin-bottom: 7px;
  }
  .user-list {
    height: 365px;
    overflow-y: scroll;
    position: relative;
  }
  .user-list .user {
    line-height: 35px;
  }
  .user-list .add-btn {
    position: absolute;
    right: 0;
  }
  .user-form .next-dept-id >>> .el-form-item__content {
    width: 79%;
  }
  .user-form .role-list, .user-form .audit-remark {
    width: 100%;
  }
  .user-form .role-list >>> .el-form-item__content {
    width: 83%;
  }
  .user-form .role-list >>> .el-select {
    width: 100%;
  }
  .user-form .audit-remark >>> .el-form-item__content {
    width: 83%;
  }
</style>
